<?php
namespace app\live\controller;
use think\Controller;
use think\Db;
use app\miniprogram\controller\Base as miniprogramBase;
use app\live\model\Lives;
use AlibabaCloud\Client\json;
use GuzzleHttp\json_encode;
use app\weixin\controller\Message;
use app\weixin\controller\Base as WBase;
/**
 * 公共接口
 */
class Live extends Controller
{
	protected $app;
	protected $lives_model;
	protected function _initialize()
	{
		parent::_initialize();
		$this->app = new miniprogramBase();
		$this->lives_model = new Lives();
	}

	/**
	 * 获取直播回放源视频
	 * @author zhoulei
	 */
	public function getinfo(){
		$room_id = input('room_id');
		if (!$room_id){
			$this->error('直播间ID不能为空');
		}
		$start = input('start',0,'intval');
		$limit = input('limit',10,'intval');
		$res = $this->app->getLiveInfo($room_id,$start,$limit);
		if ($res['code']==1){
			$this->success('获取成功',$res['data']);
		}
		$this->error($res['msg']);
	}
  	/**
	 * 获取推拉流地址
	 * @author zhoulei
	 */
	public function get_push(){
             //取随机5位字符串
      $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
      $name=substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),5);
      
              /*
      传入自定义参数，即传入应用名称和流名称
      */
      $AppName = 'zhibo';
      $StreamName = $name;

      /*
      时间戳，有效时间
      */
      $time = time() + 1800;

      /*vhost
      加密key，即直播后台鉴权里面自行设置
      */
      $key = 'JZgVKplC3N';

      $strpush = "/$AppName/$StreamName-$time-0-0-$key";
      /*
      里面的直播推流中心服务器域名、vhost域名可根据自身实际情况进行设置
      */
      $tuiliu='rtmp://tuiliu.tuiliu.com/';//这里需要配置好推流域名和播放域名
      $baofang='rtmp://bofang.bofang.com/';
      $pushurl = $tuiliu.$AppName/$StreamName?auth_key=$time-0-0-".md5($strpush);

      $strviewrtmp = "/$AppName/$StreamName-$time-0-0-$key";
      $strviewflv = "/$AppName/$StreamName.flv-$time-0-0-$key";
      $strviewm3u8 = "/$AppName/$StreamName.m3u8-$time-0-0-$key";

      $rtmpurl = $baofang.$AppName/$StreamName?auth_key=$time-0-0-".md5($strviewrtmp);
      $flvurl =$baofang.$AppName/$StreamName.flv?auth_key=$time-0-0-".md5($strviewflv);
      $m3u8url =$baofang。$AppName/$StreamName.m3u8?auth_key=$time-0-0-".md5($strviewm3u8);

      /*
      打印推流地址，即通过鉴权签名后的推流地址
      */
      echo "打印推流地址".$pushurl.'<br>';

      /*
      打印三种直播协议播放地址，即鉴权后的播放地址
      */
      //echo $rtmpurl.'<br>';
      //echo $flvurl.'<br>';
      echo "打印播放地址".$m3u8url.'<br>';
       }
  
   	  /**
     * 创建直播间
     * @author zhoulei
     */
      
  	public function creatroom(){
      $title =input('title');
      $intro =input('intro');
      $live_cover =input('live_cover');
      $user_id =input('user_id');
      	$ret =Db::table('lives')->where('isshow',1)->where('user_id',$user_id)->order('id Desc')->find();
      if($ret){
       $data00=[
       	'code'=>0,
        'msg'=>'你已创建过房间'
       ];
         return json_encode($data00);
      }else{
       Db::startTrans();
		try{
              
         
          //参数随便写
			 $date = [
				'uniacid' =>2,
               	'created_at'=>time(),
                'end_at' => 0,
                'live_status' =>2,
                'isshow' => 1,
                'status' =>0,
                'title' =>$title,
				'sign' => '',
				'logo' =>'',
				'live_cover' =>$live_cover,
              	 'intro'=>$intro,
                'image_text_name' => '直播员',
                'image_text_image' =>'',
                'base_num' => 1000,
                'num_float' =>0,
                'float_type' => 1,
				'total_num' =>100,//虚拟人数
				'real_num' => 100,//真实人数总数
               	'user_id'=>$user_id,
		];
      		$ret =Db::table('lives')->insertGetId($date);
          
           $data2=[
                'rid' =>$rid,
                'sort' =>0,
                'uniacid' =>3,
                'setting' =>'""',
                'name' =>'互动',
                'live_id' =>$ret,
             	'isshow'=>1,
            	'type'=>1,
             	'typename'=>'chat',
             	'isyunshop'=>0,
              ];
             Db::table('navs')->insert($data2);
			Db::commit();
          	/*fopen打开远程url  get方法*/
          
           	$pushurl=$this->geturl($filename);
          	$data=[
              'pushurl'=>$pushurl,
               'live_id'=>$ret
            ];
          Db::table('lives')->where('user_id',$user_id)->update([
          'pushurl'=>$pushurl
          ]);
          	return json_encode($data);
		}catch (\ Exception $e){
			Db::rollback();
			return  '创建失败';
		}
      
      }
      
     
       
    }
  
    /**
     * 奥点云即时聊天
     * @author zhoulei
     */
    
  public function chat(){
    vendor('tis.tis');
    vendor('tis.conf');
    $id='123456789';
    $key='67fs6df6sd76fs78df6sd8f';
    $api = new \TisApi($id,$key);
    $method = $_REQUEST['method'];

    $rst = $api->$method($_REQUEST,'0da992333663e3cd6779334a78aae4a9');
    echo json_encode($rst);
  }
  
  
    /**
     * 查询我的直播间
     * @author zhoulei
     */
   public function my_video(){
      $user_id =input('user_id');
   	$ret =Db::table('lives')->where('isshow',1)->where('user_id',$user_id)->order('id Desc')->find();
     if($ret){
        $result = [
            'code' => 1,
            'msg'  => '查询成功',
            'data' => $ret,
          ];
     		return json_encode($result);
     }else{
     	  $result = [
            'code' => 0,
            'msg'  => '查询失败',
            'data' => $ret,
          ];
     		return json_encode($result);
     }
  }
  
  
   /**
     * 查询直播列表
     * @author zhoulei
     */
   public function videos(){
         
   	$ret =Db::table('lives')->where(['isshow'=>'1','uniacid'=>'2'])->order('id DESC')->select();
     if($ret){
        
     		return json_encode($ret);
     }else{
     	  $result = [
            'code' => 0,
            'msg'  => '查询失败',
            'data' => $ret,
          ];
     		return json_encode($result);
     }
  }
   /**
     * 图片上传
     * @author zhoulei
     */
public function uploads(){
    $base64 = input('image', '');//获取前端ajax发送的base64加密过的图片数据
    //利用正则表达式对传递过来的图片数据进行替换,将数据中‘,’号前面的为' '，注包括','，
    //具体怎么查看前端传的图片数据可以在前端       选择图片的回调事件中打印一下图片数据
    $image_content = preg_replace('#^data:image/\w+;base64,#i', '', $base64);
    $image_content = base64_decode($image_content);//解密base64编码的图片数据
    $pic_path = '../../data.qiersan.com/liveimg/';//定义一个保存图片的文件目录，此处是已创建的文件目录
  	$jiami= md5(md5(time())) . '.jpg';
    $pic_path .= $jiami;//根据时间生成图片名并使用md5加密，也可以前端传递一个文件名
  	
	$imgurl='liveimg/'.$jiami;
    $size = file_put_contents($pic_path, $image_content);//利用file_put_contents进行图片文件的写入
    if ($size) {
      $result = [
            'code' => 1,
            'msg'  => '上传成功',
            'data' => $imgurl,
          ];
     		return json_encode($result);
    }else {
      $result = [
            'code' => 0,
            'msg'  => '上传失败',
            'data' => $size,
          ];
     		return json_encode($result);
    }
  }
  
 

}
